#encoding: utf-8

r'''
1、getblockhash index
2、getblock hash
3、getrawtransaction hash 1
'''
import SQLModel
import CoinRPC
import logging
import simplejson

def main():
    host = '127.0.0.1'
    port = 36345
    username = 'dirkcoinrpc'
    password = '3WHExxNjSKPNfTBTqbLwc9ULnrcLDnvnjN9e82gs8Mcx'
    dbsession = SQLModel.Session()
    cnsession = CoinRPC.coinRPC(host, port, username, password)
    count = cnsession.getblockcount()
    for blk_height in range(int(count)):
        blk_hash = cnsession.getblockhash(blk_height)
        logging.info('BLOCK:[%d]=>[%s]'%(blk_height, blk_hash))
        ####block
        blk_obj  = cnsession.getblock(blk_hash)
        block_db = SQLModel.BLOCK(
            blk_height=blk_height,
            blk_hash = blk_hash,
            blk_size = blk_obj['size'],
            blk_version = blk_obj['version'],
            blk_merkleroot = blk_obj['merkleroot'],
            blk_time = blk_obj['time'],
            blk_nonce = blk_obj['nonce'],
            blk_bits = blk_obj['bits'],
            blk_difficulty = blk_obj['difficulty']
        )
        dbsession.add(block_db)
        ####transaction
        for txitem in blk_obj['tx']:
            txobj = cnsession.getrawtransaction(txitem, 1)
            if txobj is None:
                logging.warn('TRANSACTION:[%s], Not found any transaction'%(txitem))
                break
            tx_db = SQLModel.TRANSACTION(
                tx_hash = txitem,
                tx_version=txobj['version'],
                tx_locktime=txobj['locktime'],
                tx_time = txobj['time'],
                blk_height = blk_height
            )
            dbsession.add(tx_db)
            #######v_in
            for vinitem in txobj['vin']:
                intx_hash = ''
                if vinitem.has_key('txid'):
                    intx_hash = vinitem['txid']
                vin_db = SQLModel.V_IN(
                    tx_hash = txitem,
                    intx_hash = intx_hash,
                    raw_msg = simplejson.dumps(vinitem)
                )
                dbsession.add(vin_db)
            #######v_out
            for voutitem in txobj['vout']:
                if len(voutitem['scriptPubKey'] ['addresses'])>1:
                    import pdb
                    pdb.set_trace()
                vout_db = SQLModel.V_OUT(
                    tx_hash = txitem,
                    amount=voutitem['value'],
                    address=voutitem['scriptPubKey'] ['addresses'] [0],
                    raw_msg=simplejson.dumps(voutitem)
                )
                dbsession.add(vout_db)
        if blk_height%100==0:
            dbsession.commit()
    dbsession.commit()


def initLog(log_path):
    import os,sys,copy,logging
    class MyConsoleHandler(logging.StreamHandler):
        def emit(self, record):
            myrecord = copy.copy(record)
            if os.name == 'nt':
                if isinstance(myrecord.msg, unicode):
                    myrecord.msg = myrecord.msg.encode('gbk')
                elif isinstance(myrecord.msg, str):
                    myrecord.msg = myrecord.msg.decode('utf-8').encode('gbk')
            logging.StreamHandler.emit(self, myrecord)
    logfile = os.path.join(log_path, os.path.basename(sys.argv[0]) + ".log")
    logger = logging.getLogger()
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    ####handler
    hdlr = logging.FileHandler(logfile)
    chdlr = MyConsoleHandler()
    ####settings
    hdlr.setFormatter(formatter)
    chdlr.setFormatter(formatter)
    ######logger
    logger.addHandler(hdlr)
    logger.addHandler(chdlr)
    logger.setLevel(logging.NOTSET)
    #######requests
    req_logger = logging.getLogger('requests')
    req_logger.setLevel(logging.WARNING)


if __name__ == '__main__':
    initLog('.')
    main()
